package com.ctgu.springstart.controller;

import com.ctgu.springstart.domain.JsonData;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.util.UUID;

@Controller
@PropertySource({"classpath:application.yml"})
public class FileController {

    @Value("${web.file.path}")
    private String PATH;

    @RequestMapping(value = "/api/v1/gopage")
    public Object index(){
        return "index";
    }

    @RequestMapping(value = "upload")
    @ResponseBody
    public JsonData upload(@RequestParam("head_img")MultipartFile file, HttpServletRequest request){
//        String absolutePath = new File("").getAbsolutePath();
//        String PATH = absolutePath + "/src/main/resources/static/images/";
        String name = request.getParameter("name");
        System.out.println("用户名:" + name);
        // 获取文件名
        String fileName = file.getOriginalFilename();
        System.out.println("上传的文件名为:" + fileName);
        // 获取文件的后缀名, 比如图片的jpeg，png
        String suffixName = fileName.substring(fileName.lastIndexOf("."));
        System.out.println("上传的后缀名为:" + suffixName);
        // 文件上传后的路径
        fileName = UUID.randomUUID() + suffixName;
        System.out.println("配置的路径为:" + PATH);
        File dest = new File(PATH + fileName);
        try{
            file.transferTo(dest);
            return new JsonData(0, fileName);
        }catch(Exception e){

        }
        return new JsonData(-1, "fail to save file");
    }

}
